<template>
  <div class="container" v-loading="loading">
    <h1>房屋租赁管理系统欢迎您</h1>
    <div class="user-info">
      <el-avatar :src="user.headImg" :size="160" shape="square"></el-avatar>
      <div class="user-box">
        <p class="title">用户名：</p>
        <p class="item">{{ user.name }}</p>
      </div>
      <div class="user-box">
        <p class="title">账号：</p>
        <p class="item">{{ user.username }}</p>
      </div>
      <!-- <div class="user-box">
        <p class="title">手机号：</p>
        <p class="item">{{ user.phone }}</p>
      </div>
      <div class="user-box">
        <p class="title">邮箱：</p>
        <p class="item">{{ user.username }}</p>
      </div> -->
      <div class="user-box">
        <p class="title">权限：</p>
        <p class="item">超级管理员</p>
      </div>
    </div>
    <div class="btn-box">
      <el-button class="btn" type="primary" @click="btnClick(1)"
        >修改头像</el-button
      >
      <el-button class="btn" type="primary" @click="btnClick(2)"
        >修改用户名</el-button
      >
      <el-button class="btn" type="primary" @click="btnClick(3)"
        >修改密码</el-button
      >
    </div>

    <!-- 修改头像弹窗 -->
    <el-dialog
      title="修改头像"
      :visible.sync="showAvatarDialog"
      width="30%"
      v-loading="loading"
    >
      <el-upload
        class="avatar-uploader"
        action="http://43.139.235.169:8081/cos/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img :src="userForm.avatarUrl" class="avatar" />
        <el-button slot="trigger" size="small">选择文件</el-button>
      </el-upload>
      <div slot="footer">
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="avatarConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 用户名弹窗 -->
    <el-dialog
      title="修改用户名"
      :visible.sync="showUsernameDialog"
      width="30%"
    >
      <el-form :model="userForm" :rules="userRules" ref="nameForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showUsernameDialog = false">取消</el-button>
        <el-button type="primary" @click="usernameConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="showPasswordDialog" width="30%">
      <el-form :model="userForm" :rules="passwordRules" ref="passwordForm">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="userForm.oldPassword"
            type="password"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="userForm.newPassword"
            type="password"
            show-password
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="userForm.confirmPassword"
            type="password"
            show-password
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="passwordConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import md5 from "js-md5";

export default {
  name: "IndexAdmin",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validateOld = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入原密码"));
      } else if (md5(value + this.user.salt) != this.user.password) {
        callback(new Error("旧密码不正确请确认重试"));
      } else {
        callback();
      }
    };
    const validateNew = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else if (value === this.userForm.oldPassword) {
        callback(new Error("新密码不能与旧密码相同"));
      } else {
        callback();
      }
    };
    const validateConfirm = (rule, value, callback) => {
      if (value !== this.userForm.newPassword) {
        callback(new Error("两次输入的新密码不一致"));
      } else if (!value) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    return {
      //加载状态
      loading: false,
      //获取用户信息
      user: JSON.parse(this.$store.state.info),
      //弹窗校验
      userRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
      },
      passwordRules: {
        oldPassword: [
          { required: true, trigger: "blur", validator: validateOld },
        ],
        newPassword: [
          { required: true, trigger: "blur", validator: validateNew },
        ],
        confirmPassword: [
          { required: true, trigger: "blur", validator: validateConfirm },
        ],
      },
      userForm: {
        avatarUrl: "",
        username: "",
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },

      showAvatarDialog: false,
      showUsernameDialog: false,
      showPasswordDialog: false,
    };
  },
  methods: {
    btnClick(index) {
      if (index === 1) {
        this.showAvatarDialog = true;
        this.userForm.avatarUrl = this.user.headImg;
      } else if (index === 2) {
        this.userForm.username = this.user.name;
        this.showUsernameDialog = true;
      } else if (index === 3) {
        this.showPasswordDialog = true;
      }
    },
    //上传成功后
    handleAvatarSuccess(res, file, fileList) {
      this.userForm.avatarUrl = res.resultObj;
      this.loading = false;
    },
    //上传之前
    beforeAvatarUpload(file) {
      this.loading = true;

      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
        this.loading = false;
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.loading = false;
        this.$message.error("上传头像图片大小不能超过 2MB!");
        return false;
      }
      return true;
    },
    //修改头像确认
    avatarConfirm() {
      this.loading = true;
      this.$api
        .userAddOrUpdate({
          id: this.user.id,
          headImg: this.userForm.avatarUrl,
        })
        .then((res) => {
          // console.log(res);
          if (res.code === 0) {
            this.loading = false;
            this.showAvatarDialog = false;
            //同时更新本地
            this.user.headImg = this.userForm.avatarUrl;
            this.$store.dispatch("userInfo", this.user);
            this.$message({
              message: "修改成功！",
              type: "success",
            });
          }
        });
    },
    //修改用户名确认
    usernameConfirm() {
      this.$refs.nameForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$api
            .userAddOrUpdate({
              id: this.user.id,
              name: this.userForm.username,
            })
            .then((res) => {
              // console.log(res);
              if (res.code === 0) {
                this.loading = false;
                this.showUsernameDialog = false;
                //同时更新本地
                this.user.name = this.userForm.username;
                this.$store.dispatch("userInfo", this.user);
                this.$message({
                  message: "修改成功！",
                  type: "success",
                });
              }
            });
        } else {
          this.$message({
            message: "请输入完整内容",
            type: "error",
          });
          return;
        }
      });
    },
    //修改密码确认
    passwordConfirm() {
      this.$refs.passwordForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$api
            .userAddOrUpdate({
              id: this.user.id,
              password: this.userForm.confirmPassword,
            })
            .then((res) => {
              // console.log(res);
              if (res.code === 0) {
                this.loading = false;
                this.showPasswordDialog = false;
                this.$message({
                  message: "修改成功！",
                  type: "success",
                });
              }
            });
        } else {
          this.$message({
            message: "请输入完整内容",
            type: "error",
          });
          return;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
h1 {
  text-align: center;
  margin-top: 20px;
}
.user-info {
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  .user-box {
    display: flex;
    align-items: center;
    gap: 10px;

    .title {
      font-size: 20px;
    }
    .item {
      font-size: 24px;
    }
  }
}
.btn-box {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 40px;
  margin-top: 50px;

  .btn {
    background: pink;
    border: 1px solid pink;
    &:hover {
      opacity: 0.8;
    }
  }
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.avatar {
  width: 120px;
  height: 120px;
  margin: 20px;
}
</style>
